package dbutil

import (
	"gopkg.in/yaml.v2"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"io/ioutil"
	"log"
	"strconv"
)

type DBConfig struct {
	Ip       string `yaml:"ip"`
	Port     int    `yaml:"port"`
	UserName string `yaml:"userName"`
	PassWord string `yaml:"passWord"`
	Name     string `yaml:"name"`
}

type CommonDB struct {
	// 实体名称首字母大写，不然不能解析
	DbConfig DBConfig `yaml:"database"`
}

func QueryDBConfig() DBConfig {
	// 读取YAML文件
	data, err := ioutil.ReadFile("app.yml")
	if err != nil {
		panic(err)
	}
	// 解析YAML到Config结构体
	var config CommonDB
	err = yaml.Unmarshal(data, &config)
	if err != nil {
		panic(err)
	}
	return config.DbConfig
}
func GetDB() *gorm.DB {
	var dbConfig DBConfig = QueryDBConfig()
	dsn := dbConfig.UserName + ":" + dbConfig.PassWord + "@tcp(" + dbConfig.Ip + ":" + strconv.Itoa(dbConfig.Port) + ")/" + dbConfig.Name + "?charset=utf8mb4&parseTime=True&loc=Local"
	//dsn := "root:123456@tcp(127.0.0.1:3306)/test?charset=utf8mb4&parseTime=True&loc=Local"
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
	if err != nil {
		log.Fatal("failed to connect database")
	}
	return db
}
